package com.bosc.modeling.controller;

import com.bosc.modeling.common.BaseController;
import com.bosc.modeling.common.Const;
import com.bosc.modeling.common.ResponseFactory;
import com.bosc.modeling.pojo.gen.UserEntity;
import com.bosc.modeling.service.UserService;
import com.bosc.modeling.utils.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    Object login(HttpServletRequest request,@RequestBody String body) throws JSONException {
//        System.out.println(body);
        log.info("login:"+body);
        try {
            JSONObject userInfo = new JSONObject(body);
            String userName = userInfo.getString("user_name");
            String userPass = userInfo.getString("user_pwd");
            short isAdmin = (short) userInfo.getInt("is_admin");
            List<UserEntity> users = userService.getUserByName(userName, MD5Util.encodeMD5(userPass), isAdmin);
            if(users != null && users.size() == 1){
                HttpSession session = request.getSession();
                session.setAttribute("user",users.get(0));
                return ResponseFactory.successResponse(users.get(0));
            }else{
                return ResponseFactory.failureResponse(Const.LOGIN_ERROR_CODE_1, Const.LOGIN_ERROR_DESC_1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    Object logout(HttpServletRequest request, @RequestBody String body) throws JSONException {
//        System.out.println(body);
        log.info("logout:"+body);
        try {
            HttpSession session = request.getSession();
            session.setAttribute("user",null);
            log.info("登出成功:"+body);
            return ResponseFactory.successResponse(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    Object resetPaassword( @RequestBody String body) throws JSONException {
        log.info("resetPaassword:"+body);
        try {
            JSONObject param = new JSONObject(body);
            String email = param.getString("email");
            List<UserEntity> users = userService.getUserByEmail(email);
            if (users != null && users.size() == 1){
                UserEntity user  = users.get(0);
                user.setUserPassword(MD5Util.encodeMD5("12345a"));
                userService.updateUser(user);
                log.info("重置密码成功:"+body);
                return ResponseFactory.successResponse(null);
            }else{
                log.info("邮箱不存在,重置密码失败:"+body);
                return ResponseFactory.failureResponse(null,"邮箱不存在");
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "/update_user", method = RequestMethod.POST)
    Object updateUser( @RequestBody String body) throws JSONException {
        log.info("updateUser:"+body);
        try {
            JSONObject param = new JSONObject(body);
            int id = param.getInt("id");
            UserEntity user = userService.getUserById(id);
            user.setUserPassword(MD5Util.encodeMD5(param.getString("password")));
            user.setUserName(param.getString("user_name"));
            user.setUserPhone(param.getString("phone"));
            user.setDepartment(param.getString("department"));
            userService.updateUser(user);
            log.info("个人信息更新成功:"+body);
            return ResponseFactory.successResponse(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "/check_login_state", method = RequestMethod.GET)
    Object checkLoginState(HttpServletRequest request) throws JSONException {
//        System.out.println(body);
        log.info("checkLoginState");
        try {
                HttpSession session = request.getSession();
//                log.info("session超时时长："+session.getMaxInactiveInterval()+"s");
                UserEntity user = (UserEntity)session.getAttribute("user");
            if(user != null){
                log.info("已登录");
                return ResponseFactory.successResponse(user);
            }else{
                log.info("未登录");
                return ResponseFactory.failureResponse(null,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    Object register(@RequestBody String body) throws JSONException {
//        System.out.println(body);
        log.info("register:"+body);
        try {
            JSONObject userInfo = new JSONObject(body);
            String email = userInfo.getString("email");
            List users = userService.getUserByEmail(email);
            if (users != null && users.size() > 0){
                log.info("注册失败：该邮箱已注册");
                return ResponseFactory.failureResponse("1","该邮箱已注册");
            }
            String userName = userInfo.getString("user_name");
            String phone = userInfo.getString("phone");
            String department = userInfo.getString("department");
            String userPass = userInfo.getString("password");
            UserEntity user = new UserEntity();
            user.setDepartment(department);
            user.setUserEmail(email);
            user.setIsAdmin((short)1);
            user.setTime(new Date());
            user.setUserId(UUID.randomUUID().toString());
            user.setUserPassword(MD5Util.encodeMD5(userPass));
            user.setUserPhone(phone);
            user.setUserName(userName);
            userService.insertUser(user);
            log.info("注册成功");
            return ResponseFactory.successResponse(user);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    @RequestMapping(value = "/user_list", method = RequestMethod.GET)
    Object getUserList(@RequestParam("page") int page, @RequestParam("limit") int limit) throws Exception {
//        System.out.println(body);
        try {
            PageHelper.startPage(page, limit);
            List<UserEntity> list = userService.getUserList();
            PageInfo<UserEntity> pageInfo = new PageInfo<UserEntity>(list);
            long count = pageInfo.getTotal();
            List data = pageInfo.getList();
            HashMap res = new HashMap();
            res.put("status",0);
            res.put("message","");
            res.put("total",count);
            res.put("data", data);
//            System.out.println(pageInfo);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    @RequestMapping(value = "/user_del", method = RequestMethod.POST)
    Object delUser(@RequestBody String body) throws Exception {
        System.out.println(body);
        try {
            JSONObject data = new JSONObject(body);
            JSONArray arr = data.getJSONArray("ids");

            for (int i = 0; i < arr.length(); i++) {
                int id = arr.getInt(i);
                userService.delUser(id);
            }
            return ResponseFactory.successResponse(null);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    @RequestMapping(value = "/search_user", method = RequestMethod.GET)
    Object searchUser(@RequestParam("page") int page, @RequestParam("limit") int limit, @RequestParam(defaultValue = "", value = "user_name") String user_name) throws Exception {
//        System.out.println(body);
        try {
//            JSONObject  request = new JSONObject(body);
            PageHelper.startPage(page, limit);
            List<UserEntity> list = userService.searchUser(user_name);
            PageInfo<UserEntity> pageInfo = new PageInfo<UserEntity>(list);
            long count = pageInfo.getTotal();
            List data = pageInfo.getList();
            HashMap res = new HashMap();
            res.put("status",0);
            res.put("message","");
            res.put("total",count);
            res.put("data", data);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }
}
